<template>
  <div id="user-info-set">
    <p>
      <van-uploader :after-read="afterRead" v-model="userShowImg" />
    </p>
    <van-field v-model="nickName" label="昵称" placeholder="例如:陈晨" />
    {{ userId }}
    <button @click="setUserInfo">自定义</button>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { compressImage } from "@/assets/js/compressImage";
import WebIM from "../../utils/WebIM";
export default {
  data() {
    return {
      userImgFile: "",
      userShowImg: [],
      photo: "",
      nickName: "",
    };
  },
  computed: {
    ...mapState({
      userId: (state) => state.login.userId,
    }),
  },
  methods: {
    setUserInfo() {
      let option = {
        nickname: this.nickName,
        phone: this.userId,
        avatarurl: this.userImgFile,
      };
      WebIM.conn.updateUserInfo(option).then(() => {
        this.$store.commit("setAppUserInfo",option)
      });
    },

    afterRead(file) {
      let config = {
        width: 20, // 压缩后图片的宽
        height: 20, // 压缩后图片的高
        quality: 1, // 压缩后图片的清晰度，取值0-1，值越小，所绘制出的图像越模糊
      };
      //调用压缩方法

      compressImage(file.file, config).then((result) => {
        // result 为压缩后二进制文件
        //返回压缩后的图片
        this.photo = result;
        this.userImgFile = this.photo;
      });
      if (this.userShowImg.length >= 2) {
        this.userShowImg.shift(1);
      }
    },

    //计算base64格式的图片大小，这里我是用来方便测试的，可以删除
    getImgSize(base64url) {
      let str = base64url.replace("data:image/png;base64,", "");
      let equalIndex = str.indexOf("=");
      if (str.indexOf("=") > 0) {
        str = str.substring(0, equalIndex);
      }
      let strLength = str.length;
      let fileLength = parseInt(strLength - (strLength / 8) * 2);
      let size = "";
      size = (fileLength / 1024).toFixed(2);
      let sizeStr = size + "";
      let index = sizeStr.indexOf(".");
      let dou = sizeStr.substr(index + 1, 2);
      if (dou == "00") {
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
      }
      return size;
    },
  },
};
</script>